//
//  SheetView.swift
//  eBooks
//
//  Created by JunMing on 2020/1/14.
//  Copyright © 2020 赵俊明. All rights reserved.
//

import UIKit
import SnapKit

class BaseSheetView: UIView {
    deinit { print("‼️‼️‼️类\(self.className())已经释放") }
}

// MARK: -- BookInfoShare
class BookInfoShare: BaseSheetView, SheetCompProtocol {
    private var topCover = UIImageView(frame: CGRect.zero)
    private var orCode = UIImageView(frame: CGRect.zero)
    private var name = UILabel(frame: CGRect.zero)
    private var author = UILabel(frame: CGRect.zero)
    private var content = UILabel(frame: CGRect.zero)
    private var share = UIButton(type: .system)
    
    private var logoTop = UIButton(type: .system)
    private var logoBottom = UIButton(type: .system)
    
    private var line = UIView(frame: CGRect.zero)
    var item: SheetItem? {
        willSet {
            topCover.image = newValue?.icon
            logoTop.setImage(newValue?.topLogo?.origin, for: .normal)
            name.text = newValue?.title
            author.text = newValue?.subTitle
            content.attributedText = newValue?.attrStr
            share.setTitle("分享", for: .normal)
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(topCover)
        addSubview(name)
        addSubview(author)
        addSubview(content)
        addSubview(share)
        addSubview(line)
        addSubview(logoTop)
        addSubview(logoBottom)
        addSubview(orCode)
        config()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func config() {
        backgroundColor = UIColor.RGB(255,255,255)
        layer.cornerRadius = 10
        layer.masksToBounds = true
        
        name.font = UIFont.medium(17)
        name.textAlignment = .center
        name.textColor = UIColor.RGB(31, 31, 31)
        
        content.font = UIFont.regular(15)
        content.textAlignment = .center
        content.textColor = UIColor.RGB(128,128,128)
        content.numberOfLines = 0
        
        author.font = UIFont(name: "Helvetica-Oblique", size: 13)
        author.textAlignment = .center
        author.textColor = UIColor.RGB(31, 31, 31)
        
        topCover.contentMode = .scaleAspectFill
        topCover.clipsToBounds = true
        
        share.setBackgroundImage(UIImage(named: "backgruand"), for: .normal)
        share.addTarget(self, action: #selector(shareAction), for: .touchUpInside)
        share.tintColor = UIColor.white
        
        logoTop.setImage(UIImage(named: "003")?.origin, for: .normal)
        logoTop.layer.cornerRadius = 22
        logoTop.layer.masksToBounds = true
        logoTop.layer.borderColor = UIColor.white.cgColor
        logoTop.layer.borderWidth = 2
        logoTop.isUserInteractionEnabled = false
        
        logoBottom.setImage(UIImage(named: "xioacao"), for: .normal)
        logoBottom.layer.cornerRadius = 8
        logoBottom.tintColor = UIColor.RGB(50,205,50)
        logoBottom.isUserInteractionEnabled = false
        
        line.backgroundColor = UIColor.RGB(231, 231, 231)
        
        orCode.image = UIImage(named: "orcode")
        orCode.contentMode = .scaleAspectFit
        orCode.isHidden = true
    }
    
    @objc func shareAction() {
        share.isHidden = true
        orCode.isHidden = false
        guard let image = self.screenCapture() else { return }
        share.isHidden = false
        orCode.isHidden = true
        routerEvent(eventName: kEBookShareActionEventName, info: image)
        remove(superview as! SheetbackView)
    }
    
    func updateView(){
        topCover.snp.makeConstraints { (make) in
            make.width.equalTo(self)
            make.top.equalTo(self)
            make.height.equalTo(100)
        }
        
        logoTop.snp.makeConstraints { (make) in
            make.height.width.equalTo(44)
            make.centerX.equalTo(self.snp.centerX)
            make.centerY.equalTo(topCover.snp.bottom)
        }
        
        name.snp.makeConstraints { (make) in
            make.left.equalTo(self).offset(20)
            make.right.equalTo(self.snp.right).offset(-20)
            make.top.equalTo(logoTop.snp.bottom).offset(2)
            make.height.equalTo(20)
            make.centerX.equalTo(self.snp.centerX)
        }
        
        share.snp.makeConstraints { (make) in
            make.bottom.equalTo(self.snp.bottom).offset(-10)
            make.centerX.equalTo(self.snp.centerX)
            make.width.equalTo(100)
            make.height.equalTo(30)
        }
        
        line.snp.makeConstraints { (make) in
            make.height.equalTo(1)
            make.width.equalTo(self)
            make.bottom.equalTo(share.snp.top).offset(-10)
        }
        
//        logoBottom.snp.makeConstraints { (make) in
//            make.bottom.equalTo(line.snp.top).offset(-5)
//            make.height.width.equalTo(16)
//            make.centerX.equalTo(self.snp.centerX)
//        }
        
        author.snp.makeConstraints { (make) in
            make.bottom.equalTo(line.snp.top).offset(-5)
            make.width.equalTo(name)
            make.height.equalTo(20)
            make.centerX.equalTo(self.snp.centerX)
        }
        
        content.snp.makeConstraints { (make) in
            make.bottom.equalTo(author.snp.top).offset(-3)
            make.top.equalTo(name.snp.bottom).offset(3)
            make.width.equalTo(name)
            make.centerX.equalTo(self.snp.centerX)
        }
        
        orCode.snp.makeConstraints { (make) in
            make.width.height.equalTo(40)
            make.bottom.equalTo(snp.bottom).offset(-5)
            make.centerX.equalTo(snp.centerX)
        }
    }
}

// MARK: -- BookInfoContent
import GoogleMobileAds
class BookInfoContent: BaseSheetView, SheetCompProtocol {
    var items = [AlertItem]()
    var item: SheetItem? {
        willSet {
            let item = AlertItem(title: "取消", icon: nil)
            item.priority = 100000
            items.append(item)
            if let tempItems = newValue!.models {
                for itemValue in tempItems.reversed() {
                    items.insert(itemValue, at: 0)
                }
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.RGB(240, 240, 240)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func updateView(){
        var tempConstrainr = self.snp_top
        for (index,item) in items.enumerated() {
            if let rootVc = item.rootVc {
                let adView = GADBannerView(adSize: kGADAdSizeBanner)
                adView.translatesAutoresizingMaskIntoConstraints = false
                adView.adUnitID = "ca-app-pub-5649482177498836/1892575484"
                adView.rootViewController = rootVc
                // request.testDevices = @[@"b9aed9e5dbcfbef59263a79520f18042",kGADSimulatorID];
                adView.load(GADRequest())
                addSubview(adView)
                adView.snp.makeConstraints { (make) in
                    make.width.equalTo(self)
                    make.height.equalTo(64)
                    make.top.equalTo(tempConstrainr).offset(1)
                }
                tempConstrainr = adView.snp_bottom
            }else {
                let btn = UIButton(type: UIButton.ButtonType.system)
                btn.backgroundColor = UIColor.white
                btn.tintColor = item.textColor
                btn.tag = index + 100
                btn.addTarget(self, action: #selector(touchAction(_:)), for: UIControl.Event.touchUpInside)
                btn.setTitle(item.title, for: UIControl.State.normal)
                if let image = item.icon?.origin {
                    btn.setImage(image, for: UIControl.State.normal)
                }
                if let font = item.font { btn.titleLabel?.font = font }
                addSubview(btn)
                btn.snp.makeConstraints { (make) in
                    make.width.equalTo(self)
                    make.height.equalTo(44)
                    if item.priority == 100000 {
                        make.top.equalTo(tempConstrainr).offset(6)
                    }else{
                        make.top.equalTo(tempConstrainr).offset(1)
                    }
                }
                tempConstrainr = btn.snp_bottom
            }
        }
    }
    
    @objc func touchAction(_ sender:UIButton) {
        let item = items[sender.tag - 100]
        remove(self.superview as! SheetbackView)
        if item.priority != 100000 {
            if let eventName = item.eventName {
                routerEvent(eventName: eventName, info: item)
            }
        }
    }
}

// MARK: -- BookInfoAlert
class BookInfoAlert: BaseSheetView,SheetCompProtocol {
    private var title = UILabel(frame: CGRect.zero)
    private var subTitle = UILabel(frame: CGRect.zero)
    private var leftBtn = UIButton(type: .system)
    private var rightBtn = UIButton(type: .system)
    private var spLine = UIView(frame: CGRect.zero)
    
    var item: SheetItem? {
        willSet {
            title.text = newValue?.title
            subTitle.text = newValue?.subTitle
            guard let tempItems = newValue!.models else { return }
            if tempItems.count == 2 {
                if let leftItem = tempItems.first {
                    leftBtn.setTitle(leftItem.title, for: .normal)
                    leftBtn.setBackgroundImage(leftItem.icon, for: .normal)
                    leftBtn.tag = 100
                }
                if let rightItem = tempItems.last {
                    rightBtn.setTitle(rightItem.title, for: .normal)
                    rightBtn.setBackgroundImage(rightItem.icon, for: .normal)
                    rightBtn.tag = 101
                }
            }else {
                if let leftItem = tempItems.first {
                    leftBtn.setTitle(leftItem.title, for: .normal)
                    leftBtn.setBackgroundImage(leftItem.icon, for: .normal)
                    leftBtn.tag = 100
                }
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.cornerRadius = 15
        layer.masksToBounds = true
        
        backgroundColor = UIColor.RGB(240, 240, 240)
        addSubview(title)
        addSubview(subTitle)
        addSubview(leftBtn)
        addSubview(rightBtn)
        addSubview(spLine)
        configSubView()
        leftBtn.addTarget(self, action: #selector(touchAction(_:)), for: UIControl.Event.touchUpInside)
        rightBtn.addTarget(self, action: #selector(touchAction(_:)), for: UIControl.Event.touchUpInside)
    }
    
    @objc func touchAction(_ sender:UIButton) {
        remove(self.superview as! SheetbackView)
        if let items = item!.models {
            let item = items[sender.tag - 100]
            if let eventName = item.eventName {
                routerEvent(eventName: eventName, info: item)
            }
            
            if let action = item.action {
                action(item)
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func updateView(){
        title.snp.makeConstraints { (make) in
            make.top.equalTo(self).offset(10)
            make.height.equalTo(30)
            make.centerX.equalTo(self.snp.centerX)
        }
        
        if item?.models?.count == 2 {
            leftBtn.snp.makeConstraints { (make) in
                make.right.equalTo(self.snp.centerX).offset(-10)
                make.bottom.equalTo(snp.bottom).offset(-10)
                make.width.equalTo(100)
                make.height.equalTo(30)
            }
            
            rightBtn.snp.makeConstraints { (make) in
                make.left.equalTo(self.snp.centerX).offset(10)
                make.bottom.equalTo(snp.bottom).offset(-10)
                make.width.equalTo(100)
                make.height.equalTo(30)
            }
        }else {
            leftBtn.snp.makeConstraints { (make) in
                make.centerX.equalTo(self.snp.centerX)
                make.bottom.equalTo(snp.bottom).offset(-10)
                make.width.equalTo(100)
                make.height.equalTo(30)
            }
        }
        
        spLine.snp.makeConstraints { (make) in
            make.height.equalTo(1)
            make.width.equalTo(self)
            make.bottom.equalTo(leftBtn.snp.top).offset(-10)
        }
        
        subTitle.snp.makeConstraints { (make) in
            make.left.equalTo(snp.left).offset(20)
            make.right.equalTo(snp.right).offset(-20)
            make.top.equalTo(title.snp.bottom).offset(5)
            make.bottom.equalTo(spLine.snp.top).offset(-10)
        }
    }
    
    func configSubView() {
        title.font = UIFont.medium(20)
        title.textAlignment = .center
        title.textColor = UIColor.RGB(31, 31, 31)
        
        subTitle.font = UIFont.regular(17)
        subTitle.textAlignment = .center
        subTitle.textColor = UIColor.RGB(98,98,98)
        subTitle.numberOfLines = 0
        
        let frame = CGRect.Rect(0, 0, 60, 30)
        let colors = [UIColor(hexString: "#EE9A49"),UIColor(hexString: "#EE4000")]
        leftBtn.layer.cornerRadius = 15
        leftBtn.tintColor = UIColor.white
        leftBtn.backgroundColor = UIColor.gradientColor(colors: colors, frame: frame)
        
        rightBtn.layer.cornerRadius = 15
        rightBtn.tintColor = UIColor.white
        rightBtn.backgroundColor = leftBtn.backgroundColor
        
        spLine.backgroundColor = UIColor.RGB(211, 211, 211)
    }
}

// MARK: -- BookPayView
class BookPayView: BaseSheetView,SheetCompProtocol {
    private var title = UILabel(frame: CGRect.zero)
    private var subTitle = UILabel(frame: CGRect.zero)
    private var subTitle3 = UILabel(frame: CGRect.zero)
    
    private var cancle = UIButton(type: .system)
    private var reset = UIButton(type: .system)
    private var buy = UIButton(type: .system)
    private var yinsi = UIButton(type: .system)
    private var image = UIImageView(image: UIImage(named: "vipcord"))
    
    var item: SheetItem? {
        willSet {
            if let models = newValue?.models {
                cancle.setTitle(models[0].title, for: .normal)
                reset.setTitle(models[1].title, for: .normal)
                buy.setTitle(models[2].title, for: .normal)
                yinsi.setTitle(models[3].title, for: .normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(buy)
        addSubview(yinsi)
        addSubview(cancle)
        addSubview(reset)
        addSubview(image)
        
        addSubview(title)
        addSubview(subTitle)
        addSubview(subTitle3)
        
        config()
    }
    
    @objc func buy_cancle() {
        remove(self.superview as! SheetbackView)
    }
    
    @objc func buy_reset() {
        remove(self.superview as! SheetbackView)
        if let models = item?.models,let action = models[1].action {
            action(models[1])
        }
    }
    
    @objc func buy_vip() {
        remove(self.superview as! SheetbackView)
        if let models = item?.models,let action = models[2].action {
            action(models[2])
        }
    }
    
    @objc func buy_yinsi() {
        remove(self.superview as! SheetbackView)
        if let models = item?.models,let action = models[3].action {
            action(models[3])
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func config() {
        cancle.tintColor = UIColor.white
        cancle.titleLabel?.font = UIFont.medium(20)
        cancle.addTarget(self, action: #selector(buy_cancle), for: .touchUpInside)
        
        reset.tintColor = UIColor.white
        reset.titleLabel?.font = UIFont.medium(20)
        reset.addTarget(self, action: #selector(buy_reset), for: .touchUpInside)
        
        image.contentMode = .scaleAspectFit
        
        title.text = "购买高级会员"
        title.textAlignment = .center
        title.font = UIFont.Bold(30)
        title.textColor = UIColor.white
        
        let subtitle = "💎 专题:独享无广告浏览,免广告打扰.\n🔒 服务:解锁、无限制使用全部功能.\n🔗 优先:优先添加展示个人作品."
        subTitle.attributedText = subtitle.attribute(UIFont.regular(17)!)
        subTitle.textColor = UIColor.white
        subTitle.numberOfLines = 0;
        
        let text = "❤️ 购买成功用户将能够使用所有功能并去广告。\n💙 购买时我们将向您的iTunes帐户收取付款。\n💛 购买由用户管理,可到用户的帐户设置关闭。\n🧡 购买永久有效,即使删除应用,当再次下载使用本App依然可以恢复购买。\n💚 若提供免费试用但还未结束,此时用户购买该产品,未使用部分将失效。"
        subTitle3.attributedText = text.attribute(UIFont.regular(13)!)
        subTitle3.textColor = UIColor.white
        subTitle3.numberOfLines = 0;
        
        buy.tintColor = Tools.getVip() ? UIColor.RGBValue(0xFFD700):UIColor.RGBValue(0x131415)
        buy.titleLabel?.font = UIFont.medium(17)
        buy.layer.cornerRadius = 15
        buy.backgroundColor = UIColor.white
        buy.addTarget(self, action: #selector(buy_vip), for: .touchUpInside)
        
        yinsi.tintColor = UIColor.RGBValue(0xFF4500)
        yinsi.layer.cornerRadius = 8
        yinsi.titleLabel?.font = UIFont.medium(13)
        yinsi.addTarget(self, action: #selector(buy_yinsi), for: .touchUpInside)
    }
    
    func updateView() {
        cancle.snp.makeConstraints { (make) in
            make.top.equalTo(self).offset(10)
            make.height.equalTo(30)
            make.width.equalTo(60)
            make.left.equalTo(snp.left).offset(20)
        }
        
        reset.snp.makeConstraints { (make) in
            make.top.equalTo(self).offset(10)
            make.height.equalTo(30)
            make.width.equalTo(90)
            make.right.equalTo(snp.right).offset(-20)
        }
        
        image.snp.makeConstraints { (make) in
            make.top.equalTo(cancle.snp.bottom).offset(10)
            make.width.height.equalTo(80)
            make.left.equalTo(snp.left).offset(30)
        }
        
        title.snp.makeConstraints { (make) in
            make.bottom.equalTo(image.snp.bottom)
            make.left.equalTo(image.snp.right).offset(20)
            make.right.equalTo(snp.right).offset(-20)
            make.height.equalTo(80)
        }
        
        subTitle.snp.makeConstraints { (make) in
            make.top.equalTo(image.snp.bottom).offset(20)
            make.height.equalTo(80)
            make.left.equalTo(snp.left).offset(30)
            make.right.equalTo(snp.right).offset(-30)
        }

        yinsi.snp.makeConstraints { (make) in
            make.bottom.equalTo(snp.bottom).offset(-10)
            make.height.equalTo(20)
            make.left.equalTo(snp.left).offset(70)
            make.right.equalTo(snp.right).offset(-70)
        }
        
        buy.snp.makeConstraints { (make) in
            make.bottom.equalTo(yinsi.snp.top).offset(-10)
            make.height.equalTo(35)
            make.left.right.equalTo(yinsi)
        }
        
        subTitle3.snp.makeConstraints { (make) in
            make.top.equalTo(subTitle.snp.bottom)
            make.bottom.equalTo(buy.snp.top)
            make.left.right.equalTo(subTitle)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        rectCorner()
        let colors = [UIColor.RGBValue(0xfbd786),UIColor.RGBValue(0xf7797d),UIColor.RGBValue(0x06ffdd)]
        backgroundColor = UIColor.gradientColor(colors: colors, frame: bounds)
    }
}

// MARK: -- BookTopAlert
class BookTopAlert: BaseSheetView,SheetCompProtocol {
    private var title = UILabel(frame: CGRect.zero)
    var item: SheetItem? {
        willSet { title.text = newValue!.title }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.cornerRadius = 10
        layer.masksToBounds = true
        backgroundColor = UIColor.black.component(0.8)
        title.font = UIFont.medium(15)
        title.textAlignment = .center
        title.textColor = UIColor.white
        addSubview(title)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func updateView() {
        title.snp.makeConstraints { (make) in
            make.edges.equalTo(self)
        }
        
        let deadline = DispatchTime.now() + 3
        DispatchQueue.main.asyncAfter(deadline: deadline) {
            self.remove(self.superview as! SheetbackView)
        }
    }
}

// MARK: -- BookYinSiAlert
class BookYinSiAlert: BaseSheetView,SheetCompProtocol {
    private var title = UILabel(frame: CGRect.zero)
    private var content = UITextView(frame: CGRect.zero)
    private var leftBtn = UIButton(type: .system)
    private var rightBtn = UIButton(type: .system)
    var item: SheetItem? {
        willSet { content.text = newValue?.title }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        layer.cornerRadius = 10
        layer.masksToBounds = true
        backgroundColor = UIColor.white
        
        configUI()
        
        addSubview(title)
        addSubview(leftBtn)
        addSubview(rightBtn)
        addSubview(content)
    }
    
    func configUI() {
        title.text = "欢迎使用"
        
        content.isEditable = false
        content.font = UIFont.regular(12)
        content.textColor = UIColor.gray
        
        title.font = UIFont.medium(15)
        title.textAlignment = .center
        
        leftBtn.setTitle("不同意", for: .normal)
        leftBtn.setTitleColor(UIColor.gray, for: .normal)
        leftBtn.backgroundColor = UIColor.RGB(250, 250,250)
        
        rightBtn.setTitle("同意", for: .normal)
        rightBtn.backgroundColor = UIColor.RGB(250, 250,250)
        rightBtn.setTitleColor(UIColor.RGB(80, 195, 165), for: .normal)
        leftBtn.addTarget(self, action: #selector(tongyiAction), for: .touchUpInside)
        rightBtn.addTarget(self, action: #selector(buTongyiAction), for: .touchUpInside)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func tongyiAction() {
        remove(self.superview as! SheetbackView)
        if let items = item!.models {
            if let item = items.first {
                if let eventName = item.eventName {
                    routerEvent(eventName: eventName, info: item)
                }
                
                if let action = item.action {
                    action(item)
                }
            }
        }
    }
    
    @objc func buTongyiAction() {
        remove(self.superview as! SheetbackView)
        EBookDefault.setBool(true, "yinsi")
        if let items = item!.models {
            if let item = items.last {
                if let eventName = item.eventName {
                    routerEvent(eventName: eventName, info: item)
                }
                
                if let action = item.action {
                    action(item)
                }
            }
        }
    }
    
    func updateView() {
        
        title.snp.makeConstraints { (make) in
            make.top.equalTo(self.snp.top).offset(5)
            make.height.equalTo(44)
            make.centerX.equalTo(self.snp.centerX)
        }
        
        leftBtn.snp.makeConstraints { (make) in
            make.left.equalTo(self)
            make.bottom.equalTo(snp.bottom)
            make.width.equalTo(self).multipliedBy(0.5)
            make.height.equalTo(44)
        }
        
        rightBtn.snp.makeConstraints { (make) in
            make.right.equalTo(self)
            make.bottom.equalTo(snp.bottom)
            make.width.equalTo(self).multipliedBy(0.5)
            make.height.equalTo(44)
        }
        
        content.snp.makeConstraints { (make) in
            make.top.equalTo(title.snp.bottom).offset(3)
            make.bottom.equalTo(rightBtn.snp.top).offset(-10)
            make.left.equalTo(snp.left).offset(20)
            make.right.equalTo(snp.right).offset(-20)
        }
    }
}
